<?php

namespace Twoir\Anroute\Routing;

class RouteDispatcher
{
    public function dispatch(array $routes, string $requestUri, string $requestMethod): void
    {
        foreach ($routes as $route) {

            $pattern = $this->convertToRegex($route['path']);

            if (preg_match($pattern['regex'], $requestUri, $matches) && $route['method'] === $requestMethod) {

                // Remove full match
                array_shift($matches);
                $handler = $route['handler'];
                call_user_func_array([new $handler[0](), $handler[1]], $matches);
                return;
            }
        }

        http_response_code(404);
        echo "404 Not Found";
    }

    private function convertToRegex(string $path): array
    {
        $tokens = [];
        $pattern = preg_replace_callback(
            '#\{(\w+)(?::([^}]+))?\}#',
            function($matches) use (&$tokens) {
                $paramName = $matches[1];
                $regex = isset($matches[2]) ? $matches[2] : '[^/]+';
                $tokens[] = $paramName;
                return '(' . $regex . ')';
            },
            $path
        );

        return [
            'regex' => '#^' . $pattern . '$#',
            'tokens' => $tokens
        ];
    }
}
